package com.xye.auth.base.config;

import com.xye.auth.base.entity.LoginUser;
import com.xye.auth.base.mapper.LoginUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 根据用户名获取用户<br>
 * <p>
 * 密码校验请看下面两个类
 * @author yag
 * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
//        log.info("尝试获取当前用户信息:{}", username);
        if (StringUtils.isBlank(username)) {
//            log.info("登录用户属性为空:{}", username);
//            return new LoginUser();
            throw new AuthenticationCredentialsNotFoundException("登录用户属性为空");
        }
    	LoginUser loginAppUser = loginUserMapper.getByUser(username);
//        log.info("已从权限中心获取当前用户信息:{}", loginAppUser);
        //是否启用 1 启用 0 禁用 默认为1
        Long activeFlag =loginAppUser.getActiveFlag();
        //是否锁住 1 锁住 0 未锁 默认为0
        Long lockFlag =loginAppUser.getLockFlag();
        if (null==loginAppUser || StringUtils.isBlank(loginAppUser.getUserId()))  {
//            log.info("用户不存在:{}", username);
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        } else if ( 0==activeFlag ) {
//            log.info("用户已禁用:{}", username);
            throw new DisabledException("用户已作废");
        } else if ( 1==lockFlag ) {
//            log.info("用户已锁住:{}", username);
            throw new DisabledException("用户已锁住");
        }
//        List<ScmcRole> roleBeans = baseUserClient.getUserRole(loginAppUser.getUserId());
//        log .info("当前用户角色信息: "+roleBeans);

        //把当前用户的角色塞入当前用户实体
//        loginAppUser.setRoleBeans(roleBeans);
//        log.info("认证用户信息 权限获取 loginAppUser.getAuthorities():"+loginAppUser.getAuthorities());
//        log.info("认证用户信息获取 loginAppUser:"+loginAppUser);
        return loginAppUser;
    }

}
